package com.migraine.service.impl;

import com.migraine.mapper.RoomsMapper;
import com.migraine.mapper.UsersMapper;
import com.migraine.model.Rooms;
import com.migraine.model.Users;
import com.migraine.service.RoomsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RoomsServiceImpl implements RoomsService {
    @Autowired
    private RoomsMapper roomsMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public boolean insertRoom(int id, String roomname, String creator, Date date, int limit, int type, String password, int secret) {
        return roomsMapper.insertRoom(id, roomname, creator, date, limit, type, password, secret);
    }


    @Override
    public boolean deleteRoom(int id) {
        // 成功删除返回true ，没有此id的话返回false
        return roomsMapper.deleteRoom(id);
    }

    @Override
    public int getRoomType(int id) {
        Integer ans;
        ans = roomsMapper.getRoomType(id);
        if (ans != null) return ans;
        // 如果没有搜索到返回-1
        return -1;
    }

    @Override
    public List<Integer> getAllId() {
        // 如果没有房间，则返回一个长度为0的数组
        List<Integer> ans = roomsMapper.getAllId();
        return ans;
    }

    /**
     * 按时间倒序排列房间列表（最新最前面），将用户名字替换为用户id
     * @return  roomsList
     */
    @Override
    public List<Rooms> getAllRooms() {
        List<Users> usersList = usersMapper.getAllUsers();
        List<Rooms> roomsList = roomsMapper.getAllRooms();
        //将房间里的uid设置为用户名
        for (Rooms room : roomsList) {
            for (Users user : usersList) {
                if (user.getUid().equals(room.getCreator())) {
                    room.setCreator(user.getUsername());
                    break;
                }
            }
        }
        return roomsList;
    }

    /**
     * 根据房间id返回房间对象
     * @param roomId    房间id
     * @return  Rooms对象
     */
    @Override
    public Rooms getRoomsById(int roomId) {
        return roomsMapper.getRoomsById(roomId);
    }

    @Override
    public String getRoomPasswordById(String roomId) {

        return roomsMapper.getRoomPasswordById(roomId);
    }


}
